package com.lovo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lovo.config.RedisCacheUtil;
import com.lovo.dao.IMovieDao;
import com.lovo.dao.IUserDao;
import com.lovo.entity.CarEntity;
import com.lovo.entity.UserEntity;
import com.lovo.util.CacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author lyl
 * description:
 */
@RestController
@RequestMapping
public class UserController {
    @Autowired
    private IUserDao userDao;
    @Autowired
    private IMovieDao movieDao;
    @Autowired
    private RedisCacheUtil redisCacheUtil;


    @GetMapping("userLogin/{username}/{password}")
    private UserEntity userLogin(@PathVariable String username, @PathVariable String password) {
        QueryWrapper<UserEntity> qw = new QueryWrapper<>();
        qw.eq("username", username);
        qw.eq("password", password);
        UserEntity u = userDao.selectOne(qw);
        return u;
    }

    @GetMapping("addMovieToList/{userId}/{movieId}")
    private String addMovieToList(@PathVariable int userId, @PathVariable int movieId) {
        UserEntity userEntity = userDao.selectById(userId);
        //此处需要使用Redis来查询是否有用户的购物车缓存
        Boolean flag = redisCacheUtil.hasKey(userEntity.getUsername());
        if (flag) {
            //如果有取出购物车后查找是否有同一购物车
            Object object = redisCacheUtil.get(userEntity.getUsername());
            String txt = JSONArray.toJSONString(object);
            List<CarEntity> list = JSON.parseArray(txt, CarEntity.class);
            System.out.println("redis中：" + list.toString() + "\n" + redisCacheUtil.get(userEntity.getUsername()).getClass());
            for (int i = 0; i < list.size(); i++) {
                System.out.println(list.get(i));
                if (movieId == list.get(i).getMovieEntity().getMovieId()) {
                    //如果电影id相同则意味着有此电影存在，可以直接增加票数1
                    int x = list.get(i).getNum();
                    list.get(i).setNum(x + 1);
                    redisCacheUtil.set(userEntity.getUsername(), list, 1800);
                    return "更新完毕";
                }
            }
            //循环结束后都没有找到的话就证明购物车集合中并未包含当前的电影，需要新建并放入
            CarEntity carEntity = new CarEntity();
            carEntity.setMovieEntity(movieDao.selectById(movieId));
            carEntity.setNum(1);
            list.add(carEntity);
            //使用redis传回
            redisCacheUtil.set(userEntity.getUsername(), list, 1800);
        } else {
            //此用户没有的话，则新建购物车并放入
            CarEntity c = new CarEntity();
            c.setMovieEntity(movieDao.selectById(movieId));
            c.setNum(1);
            List<CarEntity> list = new ArrayList<>();
            list.add(c);
            //使用redis保存
            redisCacheUtil.set(userEntity.getUsername(), list, 1800);
        }
        return "添加购物车成功";
    }

    @GetMapping("getFromRedis/{userId}")
    private Object getFromRedis(@PathVariable int userId) {
        UserEntity userEntity = userDao.selectById(userId);
        //从redis中取出数据
        return redisCacheUtil.get(userEntity.getUsername());
    }

    @DeleteMapping("delFromRedis/{userId}")
    private boolean delFromRedis(@PathVariable int userId) {
        UserEntity userEntity = userDao.selectById(userId);
        redisCacheUtil.del(userEntity.getUsername());
        return true;
    }


    @GetMapping("findByCache/{userId}")
    private Object findByCache(@PathVariable String userId) {
        if (!CacheUtil.bloomFilter.mightContain(userId)) {
            return null;
        }
        String key = userId + "_";
        int time = new Random().nextInt(120) + 60;
        Boolean flag = redisCacheUtil.hasKey(key);
        if (flag) {
//            System.out.println("进入缓存");
            Object o = redisCacheUtil.get(key);
            return o;
        } else {
//            System.out.println("进入数据库查询");
            UserEntity us = userDao.selectById(userId);
            redisCacheUtil.set(key, us, time);
            return us;
        }
    }
}
